package com.pay.ioopos.fragment;

import com.aggregate.pay.sanstar.SanstarApiFactory;
import com.aggregate.pay.sanstar.bean.Result;
import com.aggregate.pay.sanstar.bean.TerminalBindData;
import com.aggregate.pay.sanstar.bean.TerminalBindResult;
import com.aggregate.pay.sanstar.support.Client;
import com.pay.ioopos.ApiFactory;
import com.pay.ioopos.DataFactory;
import com.pay.ioopos.DataStore;
import com.pay.ioopos.StatusListener;
import com.pay.ioopos.activity.ShopActivity;
import com.pay.ioopos.service.PantService;
import com.pay.ioopos.service.ReportService;

import static com.pay.ioopos.fragment.TipFragment.TipType.WAIT;

public class ShopBindFragment extends TipVerticalFragment {
    private StatusListener listener;
    private String code;

    public ShopBindFragment(StatusListener listener) {
        super(WAIT, "正在自动绑定");
        this.listener = listener;
    }

    public ShopBindFragment(String code, StatusListener listener) {
        super(WAIT, "正在绑定设备");
        this.code = code;
        this.listener = listener;
    }

    @Override
    public boolean useNetwork() {
        return true;
    }

    @Override
    public void execute() throws Exception {

        TerminalBindData apiData = new TerminalBindData();
        apiData.setCode(code);

        Client<TerminalBindData, TerminalBindResult> client = SanstarApiFactory.terminalBind(ApiFactory.initApi());

        Result<TerminalBindResult> apiResult = client.execute(apiData);

        if (apiResult.getStatus() != Result.Status.OK) {
            if (null == code || code.isEmpty()) {
                setMainFragment(new ShopBindScanFragment((ShopActivity)getActivity()));
                return;
            }
            onError("[" + apiResult.getCode() + "]" + apiResult.getMessage());
            return;
        }

        TerminalBindResult bindResult = apiResult.getData();

        DataStore store = DataFactory.getDataStore();
        store.setMerchNo(bindResult.getMerchNo());
        store.setTerminalNo(bindResult.getTerminalNo());
        store.setTransKey(bindResult.getTransKey());
        store.setTransPrefix(bindResult.getTransPrefix());

        ReportService.resetService();
        PantService.online(true);

        onSuccess();
    }

    @Override
    public void onError(String msg) {
        speak("设备绑定失败");
        listener.onError(msg);
    }

    private void onSuccess() {
        speak("设备绑定成功");
        listener.onSuccess("设备绑定成功");
    }

}
